package org.mj.im.server.netty.tcp;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.mj.im.server.codec.TcpSocketMessageDecoder;
import org.mj.im.server.codec.TcpSocketMessageEncoder;
import org.mj.im.server.netty.IMNettyServer;
import org.mj.im.server.netty.handler.IMChannelHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@ConditionalOnProperty(prefix = "im.server.tcp",value = "enable",havingValue = "true",matchIfMissing = true)
public class TcpServer implements IMNettyServer {
    private final Logger logger = LoggerFactory.getLogger(TcpServer.class);
    private volatile boolean ready = false;
    @Value("${im.server.tcp.port}")
    private int port;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    @Override
    public boolean ready() {
        return ready;
    }

    @Override
    public void start() {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new IdleStateHandler(120,0,0, TimeUnit.SECONDS));
                        pipeline.addLast("encode",new TcpSocketMessageEncoder());
                        pipeline.addLast("decode",new TcpSocketMessageDecoder());
                        pipeline.addLast("handler",new IMChannelHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG,5)
                .childOption(ChannelOption.SO_KEEPALIVE,true);
        try{
            bootstrap.bind(port).sync().channel();
            this.ready = true;
            logger.info("TcpServer started on port {}", port);
        }catch (InterruptedException e){
            logger.error("TcpServer start error", e);
        }
    }

    @Override
    public void stop() {
        if (bossGroup != null && !bossGroup.isShutdown() && !bossGroup.isShuttingDown()) {
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null && !workerGroup.isShutdown() && !workerGroup.isShuttingDown()) {
            workerGroup.shutdownGracefully();
        }
        this.ready = false;
        logger.info("TcpServer stopped");
    }
}
